package com.redxiii.tracplus.ejb.session;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.ejb.Stateless;

import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.joda.time.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.tracplus.ejb.entity.Wiki;

/**
 * @author Daniel Filgueiras
 * @since 19/08/2011
 */
@Stateless
@SuppressWarnings("unchecked")
public class WikiDaoImpl extends HibernateDaoImpl<Wiki> implements WikiDao {

	private static final Logger logger = LoggerFactory.getLogger(WikiDaoImpl.class);
	
	@Override
	public List<Wiki> loadAll() {
		logger.warn("Can not perform this select!!!");
		return Collections.EMPTY_LIST;
	}

	public Map<String,Integer> getRecentWikis() {
		List<RecentWiki> recentWikis = createCriteria()
			.setProjection(
				Projections.projectionList()
					.add(Projections.max("wikiPk.version").as("version"))
					.add(Projections.groupProperty("wikiPk.name").as("name")))
			.setResultTransformer(Transformers.aliasToBean(RecentWiki.class))
			.list();
		
		Map<String,Integer> wikis = new TreeMap<String, Integer>();
		for (RecentWiki wiki : recentWikis) {
			wikis.put(wiki.getName(), wiki.getVersion());
		}
		return wikis;
	}
	
	public Wiki getWiki(String name, Integer version) {
		return (Wiki) createCriteria()
			.add(Restrictions.eq("wikiPk.name", name))
			.add(Restrictions.eq("wikiPk.version", version))
			.uniqueResult();
	}

	public List<Wiki> getTipsByAuthor(String author) {
		// TODO
		return Collections.EMPTY_LIST;
	}

	public List<Wiki> getTipsByInterval(Interval interval) {
		// TODO
		return Collections.EMPTY_LIST;
	}
}

class RecentWiki implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private String name;
	private Integer version;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getVersion() {
		return version;
	}
	public void setVersion(Integer version) {
		this.version = version;
	}
}